import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_trip/navigator/tab_navigator.dart';

import 'dart/async.dart';
import 'dart/class1.dart';
import 'dart/class2.dart';
import 'dart/dart3feature1.dart';
import 'dart/dart3feature2.dart';
import 'dart/datatype.dart';
import 'dart/exception.dart';
import 'dart/function.dart';
import 'dart/generic.dart';
import 'dart/isolate.dart';
import 'dart/operator.dart';
import 'dart/other.dart';
import 'dart/package/demo.dart';
import 'dart/statement.dart';
import 'dart/summary.dart';
import 'helper.dart';
import 'pages/login_page.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo'),
      routes: {
        "lib.pages.login_page.dart": (context) => const LoginPage(),
        "lib.navigator.tab_navigator.dart": (context) => TabNavigator(),

        "lib.dart.summary.dart": (context) => const DartSummary(),
        "lib.dart.datatype.dart": (context) => const DartDatatype(),
        "lib.dart.operator.dart": (context) => const DartOperator(),
        "lib.dart.statement.dart": (context) => const DartStatement(),
        "lib.dart.exception.dart": (context) => const DartException(),
        "lib.dart.function.dart": (context) => const DartFunction(),
        "lib.dart.class1.dart": (context) => const DartClass1(),
        "lib.dart.class2.dart": (context) => const DartClass2(),
        "lib.dart.generic.dart": (context) => const DartGeneric(),
        "lib.dart.other.dart": (context) => const DartOther(),
        "lib.dart.package.demo.dart": (context) => const DartPackage(),
        "lib.dart.async.dart": (context) => const DartAsync(),
        "lib.dart.isolate.dart": (context) => const DartIsolate(),
        "lib.dart.dart3feature1.dart": (context) => const Dart3Feature1(),
        "lib.dart.dart3feature2.dart": (context) => const Dart3Feature2(),
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Node>? _siteMap;

  Future<void> _loadSiteMap() async {
    _siteMap = <Node>[];

    var str = await rootBundle.loadString('assets/README.md');
    var list = str.split("\n");
    Node? n;
    for (int i = 0; i < list.length; i++) {
      var line = list[i];
      if (line.startsWith("###")) {
        n = Node(line.substring(4).trim(), "", <Node>[]);
        _siteMap!.add(n);
      } else if (n != null && line.contains(". ")) {
        n.node.add(Node(
            line.trim(),
            list[++i]
                .substring(list[i].indexOf("-") + 2)
                .trim()
                .replaceAll("/", "."),
            <Node>[]));
      }
    }
    print(jsonEncode(_siteMap));
  }

  @override
  void initState() {
    /// 每帧都回调，经测试 flutter 是 60 帧刷新率
    SchedulerBinding.instance.addPersistentFrameCallback((timeStamp) {
      /// log("$timeStamp");
      /// 有下面这句则每帧回调，没有下面这句则每次渲染时回调
      SchedulerBinding.instance.scheduleFrame();
    });

    /// 判断当前是否是 release 模式
    if (kReleaseMode) {
      log("release 模式");
    } else {
      log("debug 模式");
    }

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _loadSiteMap(),
        builder: (context, snapshot) {
          if (snapshot.connectionState != ConnectionState.done) {
            return Container(
              color: Colors.orange,
              child: const Center(
                child: MyText("loading"),
              ),
            );
          }

          return Scaffold(
            appBar: AppBar(
              title: Text(widget.title),
            ),
            backgroundColor: Colors.yellow[200],
            body: ListView.builder(
              itemBuilder: (context, index) {
                return ExpansionTile(
                  initiallyExpanded: false,
                  title: Text(
                    _siteMap![index].title,
                  ),
                  collapsedBackgroundColor: Colors.yellow[200],
                  backgroundColor: Colors.green[200],
                  collapsedTextColor: Colors.black,
                  textColor: Colors.black,
                  collapsedIconColor: Colors.black,
                  iconColor: Colors.black,
                  children: _siteMap![index]
                      .node
                      .map(
                        (e) => GestureDetector(
                          child: Container(
                            alignment: Alignment.centerLeft,
                            color: Colors.orange,
                            child: Padding(
                              padding: const EdgeInsets.only(
                                  left: 10, right: 10, top: 10, bottom: 10),
                              child: Text(
                                e.title,
                                textAlign: TextAlign.left,
                                style: const TextStyle(
                                  fontSize: 16,
                                  color: Colors.white,
                                  backgroundColor: Colors.transparent,
                                ),
                              ),
                            ),
                          ),
                          onTap: () {
                            Navigator.pushNamed(context, e.url);
                          },
                        ),
                      )
                      .toList(),
                );
              },
              itemCount: _siteMap!.length,
            ),
          );
        });
  }
}

class Node {
  String title;
  String url;
  List<Node> node;

  Node(this.title, this.url, this.node);
}
